package com.xd.cloud.common;

import org.springframework.core.io.PathResource;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author wangtao
 * @class_name GlobalConfig
 * @description properties文件读取，加载到上下文中
 * @create 2017/12/7
 */
@Service
public class GlobalConfig {
    private static Logger logger = Logger.getLogger(GlobalConfig.class.getName());

    public void loadProperties(ServletContext servletContext) {

        String realPath = servletContext.getRealPath("/");
        try {
            PathResource pr = new PathResource(realPath+"\\properties\\baseConfig\\cloudvehicle.properties");
            ResourcePropertySource resourcePropertySource = new ResourcePropertySource(pr);
            String load_config = (String)resourcePropertySource.getProperty("load_config");
            String[] strings = load_config.split(",");
            if(strings != null){
                for (String p :strings){
                    PathResource _pr = new PathResource(realPath+"\\properties\\"+p+"\\cloudvehicle.properties");
                    ResourcePropertySource _rp = new ResourcePropertySource(_pr);
                    Map<String, Object> source = _rp.getSource();
                    logger.info(p+"---->"+source);
                    servletContext.removeAttribute(p);
                    servletContext.setAttribute(p,source);
                    _rp= null;
                    _pr = null;
                }
            }
            resourcePropertySource = null;
            pr = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
